package com.nf.health.app.homepage.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.DoctorDetectionAdapter;
import com.nf.health.app.adapter.MySubjectAdapter;
import com.nf.health.app.adapter.ViewHolder;
import com.nf.health.app.models.DetectionContent;
import com.nf.health.app.models.DetectionProject;
import com.nf.health.app.models.Subject;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.DensityUtil;
import com.nf.health.app.utils.ImageLoaderUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 中医体检
 * @author jiax
 *
 */
public class DoctorDetectionActivity extends BaseActivity {

	private static final String SINGLE_CHOICE = "n";
	private static final String MUTI_CHOICE = "y";
	private static final java.lang.String TAG = DoctorDetectionActivity.class.getSimpleName();
	private GridView gridview;
	private List<DetectionProject> projects;
	
	private DoctorDetectionAdapter adapter;
	private List<DetectionProject> level2Projects;
//	private FlowRadioGroup flowRadioGroup;
	private int currentPos = -1;
	private ImageView iv_title;
	private TextView tv_title_name;
	private View ll_level2;
	private ExpandableListView lv_expandable;
	private View ll_level1;
	private int itemWidth;
	/**
	 * 存储答案id的集合，List的position表示各检测项目的顺序，每个SparseArray表示对应检测项目下的题目id——答案id 的键值对。
	 */
	private final List<Map<Integer, String>> isCheckList = new ArrayList<>();
	/**
	 * 存储题目的内容
	 */
	private final List<Subject> subjects = new ArrayList<>();
	private MyExpandableAdapter myExpandableAdapter;
	private AlertDialog alertDialog;
	private int screenWidth;
	private int margin;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		screenWidth = ScreentUtils.getScreenWidth(this);
		margin = DensityUtil.dip2px(this, 15);
		itemWidth = screenWidth/5;
		
		setTitleBar(R.layout.titlebar_base);
		setContent(R.layout.activity_doctor_detection);

		initView();
		//请求第一级数据，parentId="0";
		provider.requestCategoryList("0", null, "level1");
	}
	
	private void initView() {
		ViewUtil.setText(this, R.id.titlebar_title_tv, "中医体检");
		gridview = ViewUtil.getView(this, R.id.gridview);
		iv_title = ViewUtil.getView(this, R.id.iv_title);
		tv_title_name = ViewUtil.getView(this, R.id.tv_title_name);
		ll_level1 = ViewUtil.getView(this, R.id.ll_level1);
		ll_level2 = ViewUtil.getView(this, R.id.ll_level2);
		lv_expandable = ViewUtil.getView(this, R.id.lv_expandable);
		View btn_all_finish = ViewUtil.getView(this, R.id.btn_all_finish);
		TextView titlebar_right_tv = ViewUtil.getView(this, R.id.titlebar_right_tv);
		titlebar_right_tv.setVisibility(View.VISIBLE);
		titlebar_right_tv.setText("历史记录");
		titlebar_right_tv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO 体检记录
				Bundle bundle = new Bundle();
				bundle.putString("type", "medic");
				ActivityUtils.showActivity(DoctorDetectionActivity.this, DetectionHistoryListActivity.class, bundle);
			}
		});

		btn_all_finish.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//TODO
				Map<Integer, String> answerIds = new HashMap<>();
				for (int i = 0; i < isCheckList.size(); i++) {
					for (Map.Entry<Integer, String> entry : isCheckList.get(i).entrySet()){
						answerIds.put(entry.getKey(), entry.getValue());
					}
				}
				if(answerIds.size()>0){
					String json = new Gson().toJson(answerIds);
					showDialog(json);
				}else{
					showToast("您还未选择症状~");
				}
				
			}

		});
		gridview.setOnItemClickListener(new OnItemClickListener() {


			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				/*
				 * 1.记录当前positon，方便设置背景状态
				 * 2.请求接口数据
				 * 3.更新二级标题和头像
				 */
				if(currentPos != -1){
					//设置前一个背景色
					if(isCheckList.get(currentPos)!=null && isCheckList.get(currentPos).size()>0){
						projects.get(currentPos).setmStatus(DetectionProject.STATUS_OK);
					}else{
						projects.get(currentPos).setmStatus(DetectionProject.STATUS_NONE);
					}
				}
				currentPos = position;
				projects.get(position).setmStatus(DetectionProject.STATUS_GOING);
				adapter.notifyDataSetChanged();
				
				provider.requestCategoryList(null, String.valueOf(projects.get(position).getId()), "level2");
				
				ImageLoaderUtils.getinstance(parent.getContext()).getImageNoDefault(iv_title, projects.get(position).getImg());
				tv_title_name.setText(projects.get(position).getName());
			}
		});	
		lv_expandable.setOnChildClickListener(new OnChildClickListener() {
			

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				DetectionContent content = level2Projects.get(groupPosition).getList().get(0);
				Subject subject = subjects.get(currentPos);
				String choose = content.getChoose();
				if(SINGLE_CHOICE.equals(choose)){
					//TODO 单选
					Map<String, String> map = content.getDetail().get(childPosition);
					//题目的id
					int subjectId = content.getId();//获取题目id
					String resultId = "";
					//存放题目的map
					Map<String, String> subjectMap = subject.getMap();
					if(subjectMap == null){
						subjectMap = new HashMap<>();
					}
					for (Map.Entry<String, String> entry : map.entrySet()) {
						resultId = entry.getKey();
						//key存放的是小标题内容
						subjectMap.put(level2Projects.get(groupPosition).getName(), entry.getValue());
					}
					LogUtil.e(TAG, "题目id:"+subjectId+">>>答案id:"+resultId);
					if(resultId.equals(isCheckList.get(currentPos).get(subjectId))){
						isCheckList.get(currentPos).remove(subjectId);
						subject.getMap().remove(level2Projects.get(groupPosition).getName());
					}else{
						isCheckList.get(currentPos).put(subjectId, resultId);
						subject.setMap(subjectMap);
					}
					myExpandableAdapter.notifyDataSetChanged();
				}else{
					//TODO 多选   resultId通过拼接字符串形式put 题目也使用特殊字符间隔进行拼接
					Map<String, String> map = content.getDetail().get(childPosition);
					//题目的id
					int subjectId = content.getId();//获取题目id
					String resultId = "";
					//存放题目的map
					Map<String, String> subjectMap = subjects.get(currentPos).getMap();
					if(subjectMap == null){
						subjectMap = new HashMap<>();
					}
					for (Map.Entry<String, String> entry : map.entrySet()) {
						//获取症状的key值
						resultId = entry.getKey();
						//key存放的是小标题内容，由于涉及到多选，key存放的是症状的id
						subjectMap.put(entry.getKey(), entry.getValue());
					}
					subject.setMap(subjectMap);
					String resultIds = isCheckList.get(currentPos).get(subjectId);
					if(TextUtils.isEmpty(resultIds)){
						isCheckList.get(currentPos).put(subjectId, resultId);
					}else{
						//如果包含，则删除此记录
						if(resultIds.contains(resultId)){
							String answerIds = isCheckList.get(currentPos).get(subjectId);
							int indexOf = answerIds.indexOf(resultId);
							String newResult;
							if(indexOf == 0){
								if(answerIds.length()==1){//只有一个id的情况
									isCheckList.get(currentPos).remove(subjectId);
								}else{//id在第一个位置的情况
									newResult = answerIds.replace(resultId+",", "");
									isCheckList.get(currentPos).put(subjectId, newResult);
								}
							}else{//id在其他位置的情况
								newResult = answerIds.replace(","+resultId, "");
								isCheckList.get(currentPos).put(subjectId, newResult);
							}
							subject.getMap().remove(resultId);
						}else{
							resultIds+=","+resultId;
							isCheckList.get(currentPos).put(subjectId, resultIds);
						}
					}
					myExpandableAdapter.notifyDataSetChanged();
				}
				return false;
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public void handleActionSuccess(String actionName, Object object) {
		if("level1".equals(actionName)){
			ll_level1.setVisibility(View.VISIBLE);
			projects = (List<DetectionProject>)object;
			adapter = new DoctorDetectionAdapter(projects, itemWidth);
			gridview.setAdapter(adapter);
			
			//初始化空的List和map，方便get到Map对象，初始化map值
			for(int i=0;i<projects.size();i++){
				isCheckList.add(new HashMap<Integer, String>());
				//TODO 初始化答题内容
				subjects.add(new Subject(projects.get(i).getImg(), projects.get(i).getName(), null));
			}
		}else if("level2".equals(actionName)){
			ll_level2.setVisibility(View.VISIBLE);
			level2Projects = (List<DetectionProject>)object;
//			flowRadioGroup.removeAllViews();
//			for(int i = 0; i< level2Projects.size();i++){
//				RadioButton rb = getRB(level2Projects.get(i).getName());
//				flowRadioGroup.addView(rb);
//			}
			/**
			 * key存放题目的subjectId;
			 * value存放答案的resultId
			 */
//			Map<Integer, String> map = isCheckList.get(currentPos);
////			SparseArray<String> map = new SparseArray<String>();//map代表一种类型的题目，put多个问题
//			for(int i = 0;i<level2Projects.size();i++){
//				List<DetectionContent> list = level2Projects.get(i).getList();
//				if(list != null && list.size()>0){
//					int subjectId = list.get(0).getId();
//					String resultId = map.get(subjectId);
//					//避免已经选好的数据被清空
//					if(TextUtils.isEmpty(resultId)){
//						map.put(subjectId, null);
//					}
//				}
//			}
			myExpandableAdapter = new MyExpandableAdapter();
			lv_expandable.setAdapter(myExpandableAdapter);
			if(level2Projects!=null){
				for (int i = 0; i < level2Projects.size(); i++) {
					lv_expandable.expandGroup(i);
				}
			}
		}else if("commitDetail".equals(actionName)){
			Bundle bundle = new Bundle();
			bundle.putString("majorid", String.valueOf(object));
			ActivityUtils.showActivityForResult(this, DoctorSelectedActivity.class, bundle,100);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==100 && resultCode == RESULT_OK){
			finish();
		}
	}

	private class MyExpandableAdapter extends BaseExpandableListAdapter{

		@Override
		public int getGroupCount() {
			return level2Projects==null?0:level2Projects.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			List<DetectionContent> list = level2Projects.get(groupPosition).getList();
			return list==null?0:list.get(0).getDetail().size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return level2Projects.get(groupPosition);
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return level2Projects.get(groupPosition).getList().get(0).getDetail().get(childPosition);
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			ViewHolder holder = ViewHolder.get(parent, convertView, R.layout.item_group_question_title, groupPosition);
			if(isExpanded){
				holder.setImageResource(R.id.iv_arrow, R.drawable.arrow_down);
			}else{
				holder.setImageResource(R.id.iv_arrow, R.drawable.arrow_right_small);
			}
			holder.setText(R.id.tv_name, level2Projects.get(groupPosition).getName());
//			lv_expandable.expandGroup(groupPosition);
			return holder.getConvertView();
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			DetectionContent content = level2Projects.get(groupPosition).getList().get(0);
			ViewHolder holder = ViewHolder.get(parent, convertView, R.layout.item_child_question_content, groupPosition);
			CheckBox cb_content = holder.getView(R.id.cb_content);
			Map<String, String> contentMap = content.getDetail().get(childPosition);
			Map<Integer, String> sparseArray = isCheckList.get(currentPos);
			for (Map.Entry<String, String> entry : contentMap.entrySet()) {
				cb_content.setText(entry.getValue());
				
				if(SINGLE_CHOICE.equals(content.getChoose())){
					//map的value存放的是resultId，通过题目id判断答案是否被选中
					String resultId = sparseArray.get(content.getId());
	 				if(entry.getKey().equals(resultId)){
						cb_content.setChecked(true);
					}else{
						cb_content.setChecked(false);
					}
				}else if(MUTI_CHOICE.equals(content.getChoose())){
					String resultIds = sparseArray.get(content.getId());
					if(!TextUtils.isEmpty(resultIds)){
						if(resultIds.contains(entry.getKey())){
							cb_content.setChecked(true);
						}else{
							cb_content.setChecked(false);
						}
					}else{
						cb_content.setChecked(false);
					}
				}
			}
			return holder.getConvertView();
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			/*
			 * 很重要：实现ChildView点击事件，必须返回true
			 * 子布局需要加：android:descendantFocusability="blocksDescendants"
			 */ 
			return true;
		}
		
	}

	
	private void showDialog(final String json) {
		final AlertDialog.Builder build = new AlertDialog.Builder(this);
		alertDialog = build.create();
		alertDialog.show();//必须在设置View之前调用
		alertDialog.setCanceledOnTouchOutside(true);
		View view = View.inflate(this, R.layout.dialog_doc_detection, null);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(screenWidth-margin*2, DensityUtil.dip2px(this, 400));
		params.setMargins(margin, 0, margin, 0);
		view.setLayoutParams(params);
		alertDialog.setContentView(view);
		
		Button btn_submit = (Button) alertDialog.findViewById(R.id.btn_submit);
		final EditText et_user_name = (EditText) alertDialog.findViewById(R.id.et_username);
		final EditText et_phone = (EditText) alertDialog.findViewById(R.id.et_phone);
		final EditText et_msg = (EditText) alertDialog.findViewById(R.id.et_msg);
		ListView listview = (ListView) alertDialog.findViewById(R.id.listview);
		listview.setAdapter(new MySubjectAdapter(subjects));
		//下面两行代码加入后即可弹出输入法 
		alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); 
		alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
		et_user_name.setText(PreferenceHelper.getString(PreferenceHelper.USERNICK, ""));
		et_phone.setText(PreferenceHelper.getString(PreferenceHelper.USERNAME, ""));
		btn_submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String user_name = et_user_name.getText().toString();
				String phone = et_phone.getText().toString();
				String message = et_msg.getText().toString();
				
				if(TextUtils.isEmpty(user_name) || TextUtils.isEmpty(phone)){
					showToast("姓名或电话为空");
					return;
				}
				if(alertDialog!=null){
					//检测项目提交成功
					provider.requestAddScore("8","");//添加积分
					alertDialog.dismiss();
				}
				provider.requestCommitDetail(json, user_name, phone, message, "commitDetail");
			}
		});
	}
}
